package com.xjcs.saplingplan.dialog

import android.content.Context
import com.blankj.utilcode.util.TimeUtils
import com.lxj.xpopup.core.CenterPopupView
import com.xjcs.saplingplan.R
import com.xjcs.saplingplan.adapter.RemindAdapter
import com.xjcs.saplingplan.const.setSingleClick
import com.xjcs.saplingplan.databinding.PopRemindBinding
import com.xjcs.saplingplan.utils.AppDataUtils
import com.xjcs.saplingplan.utils.DialogUtils
import java.time.LocalDate
import java.time.LocalDateTime

class RemindPop(
    private val context: Context,
    private val curRemindDays: String,
    private var curRemindTime: String,
    private val resultCallback: (String, String) -> Unit
) : CenterPopupView(context) {

    private lateinit var remindAdapter: RemindAdapter
    private lateinit var binding: PopRemindBinding

    override fun getImplLayoutId(): Int {
        return R.layout.pop_remind
    }

    override fun onCreate() {
        super.onCreate()
        binding = PopRemindBinding.bind(contentView)
        initRecyclerView()
        initListener()
    }

    private fun initListener() {
        //提醒时间
        binding.constraintTime.setSingleClick {
            showSelectTimePop()
        }
        binding.tvCancel.setSingleClick {
            dialog.dismiss()
        }
        binding.tvSure.setSingleClick {
            val selectReminds = remindAdapter.getSelectedReminds().joinToString(",")
            resultCallback.invoke(selectReminds, curRemindTime)
            dialog.dismiss()
        }
    }

    private fun initRecyclerView() {
        remindAdapter =
            RemindAdapter(context, AppDataUtils.getRepeatList(), curRemindDays, curRemindTime)
        binding.recyclerView.adapter = remindAdapter
    }

    private fun showSelectTimePop() {
        val localDate: LocalDateTime
        if (curRemindTime.isEmpty() || curRemindTime.contains(":")) {
            localDate = LocalDate.now().atTime(8, 0)
        } else {
            val timeList = curRemindTime.split(":")
            localDate = LocalDate.now().atTime(timeList[0].toInt(), timeList[1].toInt())
        }
        DialogUtils.showBasePop(context, outDismiss = true, showBg = true)
            .asCustom(RemindTimePop(context, localDate) {
                curRemindTime = TimeUtils.millis2String(it, "HH:mm")
                binding.tvTime.text = curRemindTime
                remindAdapter.initSelectTimeStr = curRemindTime
                remindAdapter.notifyDataSetChanged()
            })
            .show()
    }

}